package com.gnerv.cms.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gnerv.cms.dto.DictDTO;
import com.gnerv.cms.dto.DictSaveDTO;
import com.gnerv.cms.dto.DictSearchDTO;
import com.gnerv.cms.entity.Dict;
import com.gnerv.cms.mapper.DictItemMapper;
import com.gnerv.cms.mapper.DictMapper;
import com.gnerv.cms.service.IDictService;
import com.gnerv.cms.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * 基础平台-字典 service 实现类
 *
 * @author zhang
 * @date 2019/12/2
 **/
@Slf4j
@Service
public class DictServiceImpl implements IDictService {


    @Resource
    private DictMapper dictMapper;

    @Resource
    private DictItemMapper dictItemMapper;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean saveDict(DictSaveDTO dictSaveDTO) {
        String ukId = dictSaveDTO.getUkId();
        if (StringUtils.isEmpty(ukId)) {
            createDict(dictSaveDTO);
        } else {
            updateDict(dictSaveDTO);
        }
        return true;
    }

    @Override
    public boolean createDict(DictSaveDTO dictSaveDTO) {
        Dict dict = dictSaveDTO.convert();
        dict.setUkId(UUIDUtils.getLower());
        dictMapper.createDict(dict);
        return true;

    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean updateDict(DictSaveDTO dictSaveDTO) {
        Dict dict = dictSaveDTO.convert();
        dict.setGmtModified(LocalDateTime.now());
        dictMapper.updateById(dict);
        return true;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean deleteDict(String dictId) {
        dictItemMapper.deleteDictItemByDictId(dictId);
        dictMapper.deleteById(dictId);
        return true;
    }

    @Override
    public DictDTO selectDict(String dictId) {
        DictDTO dictDTO = dictMapper.selectDict(dictId);
        return dictDTO;
    }

    @Override
    public Page<DictDTO> listDict(DictSearchDTO dictSearchDTO, Integer current, Integer size) {
        Page<DictDTO> dictPage = dictMapper.listDict(new Page<>(current, size), dictSearchDTO);
        return dictPage;
    }

    @Override
    public Map<String, DictDTO> mapDict() {
        Map<String, DictDTO> dtoMap = dictMapper.mapDict();
        return dtoMap;
    }

    @Override
    public boolean updateDictStatus(String dictId, Integer status) {
        dictMapper.updateDictStatus(dictId, status);
        return true;
    }
}
